﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Prologis.ShifterNT.Extensions
{
    public static class ObjectExtensions
    {

        public static IEnumerable<NameValue<string, object>> GetProperties(this object item)
        {
            foreach (PropertyInfo property in item.GetType().GetProperties())
            {
                yield return new NameValue<string, object>(property.Name, () => property.GetValue(item, null));
            }
        }

        public class NameValue<TName, TValue>
        {
            public TName Name { get; private set; }
            public TValue Value { get { return valueFunction(); } }

            Func<TValue> valueFunction;

            public NameValue(TName name, Func<TValue> valueFunction)
            {
                Name = name;
                this.valueFunction = valueFunction;
            }
        }

        public static T CopyFrom<T>(this T toObject, object fromObject)
        {
            var fromObjectType = fromObject.GetType();

            foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
            {
                PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);

                if (fromProperty != null) // match found
                {
                    // check types
                    var fromType = Nullable.GetUnderlyingType(fromProperty.PropertyType) ?? fromProperty.PropertyType;
                    var toType = Nullable.GetUnderlyingType(toProperty.PropertyType) ?? toProperty.PropertyType;

                    if (toType.IsAssignableFrom(fromType))
                    {
                        toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
                    }
                }
            }

            return toObject;
        }


      

    }
}
